package com.ithiema.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ithiema.reggie.common.R;
import com.ithiema.reggie.dto.DishDto;
import com.ithiema.reggie.pojo.Category;

import com.ithiema.reggie.pojo.Dish;
import com.ithiema.reggie.pojo.DishFlavor;
import com.ithiema.reggie.service.CategoryService;
import com.ithiema.reggie.service.DishFlavorService;
import com.ithiema.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
private RedisTemplate<Object,Object> redisTemplate;
    @Transactional
    public void saveWithFlavor(DishDto dishDto){
        this.save(dishDto);
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
//增
    @PostMapping

    public R<String> save(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //删除Redis中菜品列表数据，删除缓存中菜品数据
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return R.success("新增菜品成功");
    }
//枫叶
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件，模糊查询
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);
//对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查找对象
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategroyName(categoryName);
            return dishDto;

        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);

    }
    //查
@GetMapping("/{id}")
public R<DishDto>get(@PathVariable Long id){
    DishDto dishDto = dishService.getByIdWithFlavor(id);
    return R.success(dishDto);
}
//修改
@PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
    //删除Redis中菜品列表数据，删除缓存中所有菜品数据
    Set<Object> keys = redisTemplate.keys("dish_*");
    redisTemplate.delete(keys);
        return R.success("修改成功");
}
//根据条件查询菜品数据
//@GetMapping("/list")
//public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish>queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        //查询状态
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//    List<Dish> list = dishService.list(queryWrapper);
//    return R.success(list);
//
//}
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //
        String dishRedisKey ="dish_"+ dish.getCategoryId()+"_"+dish.getStatus();
        List<DishDto> dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(dishRedisKey);
        //判断结果
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }


        LambdaQueryWrapper<Dish>queryWrapper = new LambdaQueryWrapper<>();
      //  queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getCategoryId,dish.getCategoryId());
        //查询状态
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dishDtolist = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查找对象
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategroyName(categoryName);
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;

        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(dishRedisKey,dishDtoList);

        return R.success(dishDtolist);

    }


    @PostMapping("/status/{statusCode}")
    public R<String> startSelling(@RequestParam List<Long> ids,@PathVariable int statusCode){
        log.info("起停售");

        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus,statusCode);
        qw.in(Dish::getId,ids);
        dishService.update(qw);

        return R.success("成功更改");
    }
    //删
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids){
        System.out.println(ids);
        return R.success("删除成功");
    }
}
